package com.blockmeta.bbs.immodule.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.blankj.utilcode.util.SpanUtils;
import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.businesslibrary.baselist.NewBaseListActivity;
import com.blockmeta.bbs.businesslibrary.constant.BBSShareConstant;
import com.blockmeta.bbs.immodule.Constants;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.bean.MyForumPostsPOJO;
import com.blockmeta.bbs.immodule.bean.databean.ForumPostContentBean;
import com.blockmeta.bbs.immodule.bean.databean.PostContentBean;
import com.blockmeta.bbs.immodule.dao.ChatMessage;
import com.blockmeta.bbs.immodule.modelimpl.MyForumPostModelImpl;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

public class MyForumPostSendActivity extends NewBaseListActivity<MyForumPostsPOJO.ListBean, MyForumPostsPOJO, MyForumPostModelImpl> {
    private boolean editable = false;
    private boolean chooseSingle = false;
    private SparseBooleanArray mSelectedPositions = new SparseBooleanArray();
    private int mSelectedPos = -1;
    private MyForumPostModelImpl mListModel;

    @Override
    protected void fillData(BaseViewHolder helper, final MyForumPostsPOJO.ListBean item) {
        final String type = item.getType() == null ? "0" : item.getType();
        TextView title = helper.getView(R.id.bbs_item_title);

        String attachment = item.getAttachment() == null ? "" : item.getAttachment();
        //TODO 服务器未传输此参数
        String digest = item.getDigest();
        digest = "0";
        switch (type) {
            case "0": //普通
                if (attachment.equals("2")) {
                    title.setText(new SpanUtils()
                            .append(item.getTitle() + " ")
                            .appendImage(mContext.getResources().getDrawable(R.drawable.comment_list_pic), SpanUtils.ALIGN_CENTER)
                            .create());

                } else {
                    title.setText(item.getTitle());
                }
                break;
            case "1"://投票  绿色
                initTag(item, title, digest, attachment,mContext.getResources().getDrawable(R.drawable.vote_lable));
                break;
            case "2"://商品  黑色
                initTag(item, title, digest, attachment,mContext.getResources().getDrawable(R.drawable.product_lable));
                break;
            case "3"://悬赏   橘黄
                initTag(item, title, digest, attachment,mContext.getResources().getDrawable(R.drawable.award_lable));
                break;
            case "4"://活动  红色
                initTag(item, title, digest, attachment,mContext.getResources().getDrawable(R.drawable.activity_lable));
                break;
            case "5"://辩论  //蓝色
                initTag(item, title, digest, attachment,mContext.getResources().getDrawable(R.drawable.debet_lable));
                break;
            default:
//                helper.setText(R.mPostName.bbs_item_title, item.getTitle());
                title.setText(item.getTitle());
                break;
        }
        TextView tv_content = helper.getView(R.id.bbs_item_content);
        tv_content.setText(item.getContent());


        ToggleButton toggleButton = helper.getView(R.id.tg_edit_selector);
        toggleButton.setVisibility(editable? View.VISIBLE:View.GONE);
        toggleButton.setTag(helper.getAdapterPosition());
        toggleButton.setOnCheckedChangeListener(null);
        toggleButton.setChecked(isItemChecked(helper.getAdapterPosition()));
        toggleButton.setOnCheckedChangeListener(mCheckedListener);
        toggleButton.setClickable(false);
        toggleButton.setLongClickable(false);
        ImageView view = helper.getView(R.id.bbs_item_icon);
//        Glide.with(mContext).load(item.getAuthor_info().getAvatar()).placeholder(R.drawable.yoona).into(view);
        Picasso.with(mContext).load(item.getAuthor_info().getAvatar()).placeholder(R.drawable.yoona).into(view);
        //转换时间
        String longToString = FormatUtil.StringDataToString(item.getPost_date() + "");
        helper.setText(R.id.bbs_item_author, item.getAuthor_info().getName() + "/" + longToString);
        helper.setText(R.id.bbs_item_count, item.getReplies() + "");
//        LinearLayout view1 = helper.getView(R.id.item_bbs_main);
//        view1.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (type.equals("4")) {
//                    //活动
//                    RouterHelper.startActivity(mContext, RouterPath.ACTIVE_DETAIL_ACTIVITY,item.getTid()+"");
//                } else if (type.equals("3")) {
//                    //悬赏
//                    RouterHelper.buildPath(RouterPath.BBS_REWARD_ACTIVITY)
//                            .withString("tid",item.getTid()+"")
//                            .navigation(mContext);
//                } else if (type.equals("1")) {
//                    //投票
//                    RouterHelper.buildPath(RouterPath.BBS_VOTE_ACTIVITY)
//                            .withString("tid",item.getTid()+"")
//                            .navigation(mContext);
//                } else {
//                    RouterHelper.buildPath(RouterPath.BBS_DETAIL_ACTIVITY)
//                            .withString("tid",item.getTid()+"")
//                            .navigation(mContext);
//                }
//            }
//        });

    }
    private void initTag(MyForumPostsPOJO.ListBean item, TextView title, String digest, String attachment, Drawable resId) {
        if (attachment.equals("2")) {
            if (!digest.equals("0")) {
                title.setText(new SpanUtils()
                                      .appendImage(mContext.getResources().getDrawable(R.drawable.essence_lable), SpanUtils.ALIGN_CENTER)
                                      .appendImage(resId, SpanUtils.ALIGN_CENTER)
                                      .append(" " + item.getTitle() + " ")
                                      .appendImage(mContext.getResources().getDrawable(R.drawable.comment_list_pic), SpanUtils.ALIGN_CENTER)
                                      .create());

            } else {
                title.setText(new SpanUtils()
                                      .appendImage(resId, SpanUtils.ALIGN_CENTER)
                                      .append(" " + item.getTitle() + " ")
                                      .appendImage(mContext.getResources().getDrawable(R.drawable.comment_list_pic), SpanUtils.ALIGN_CENTER)
                                      .create());
            }
        } else {
            if (!digest.equals("0")) {
                title.setText(new SpanUtils()
                                      .appendImage(mContext.getResources().getDrawable(R.drawable.essence_lable), SpanUtils.ALIGN_CENTER)
                                      .appendImage(resId, SpanUtils.ALIGN_CENTER)
                                      .append(" " + item.getTitle() + " ")
                                      .create());

            } else {
                title.setText(new SpanUtils()
                                      .appendImage(resId, SpanUtils.ALIGN_CENTER)
                                      .append(" " + item.getTitle() + " ")
                                      .create());
            }
        }
    }

    private CheckedListener mCheckedListener = new CheckedListener();

    class CheckedListener implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            if(chooseSingle){
                int position = (int) buttonView.getTag();
                if (mSelectedPos == position) {
                    setItemChecked(position, false);
                    mSelectedPos = -1;
                } else if (mSelectedPos != position && mSelectedPos != -1) {
                    //先取消上个item的勾选状态
                    setItemChecked(mSelectedPos, false);
                    mAdapter.notifyItemChanged(mSelectedPos);
                    //设置新Item的勾选状态
                    mSelectedPos = position;
                    setItemChecked(mSelectedPos, true);
                    mAdapter.notifyItemChanged(position);
                } else if (mSelectedPos == -1) {
                    mSelectedPos = position;
                    setItemChecked(mSelectedPos, true);
                    mAdapter.notifyItemChanged(position);
                }
            }else {
                int position = (int) buttonView.getTag();
                setItemChecked(position, isChecked);
            }
        }
    }

    public void setEditable(boolean editable, boolean chooseSingle) {
        this.editable = editable;
        this.chooseSingle = chooseSingle;
        mSelectedPos = -1;
    }

    public List<MyForumPostsPOJO.ListBean> getCheckedItems() {
        ArrayList<MyForumPostsPOJO.ListBean> selectList = new ArrayList<>();
        int size = mSelectedPositions.size();
        for (int i = 0; i < size; i++) {
            if(mSelectedPositions.valueAt(i)){
                selectList.add(mAdapter.getItem(mSelectedPositions.keyAt(i)));
            }
        }
        return selectList;
    }

    public int getSelectedPos() {
        return mSelectedPos;
    }


    //设置给定位置条目的选择状态
    private void setItemChecked(int position, boolean isChecked) {
        mSelectedPositions.put(position, isChecked);
    }

    //根据位置判断条目是否选中
    private boolean isItemChecked(int position) {
        return mSelectedPositions.get(position);
    }


    @Override
    protected int getItemLayout() {
        return R.layout.item_forumpost_send;
    }

    @Override
    protected View addNonScrollHeaderView() {
        return null;
    }

    @Override
    protected void doSomeBindEvent() {
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ToggleButton toggleButton = (ToggleButton) view.findViewById(R.id.tg_edit_selector);
                toggleButton.setChecked(!toggleButton.isChecked());
            }
        });
    }

    @Override
    protected View addOutHeaderView() {
        return null;
    }

    @Override
    protected void initBundle() {
        setTitleText("选择内容");
        boolean booleanExtra = getIntent().getBooleanExtra(Constants.CANCHOOSE, true);
        setEditable(booleanExtra, true);
    }

    @Override
    protected boolean showTitle() {
        return true;
    }

    @Override
    public String showRightText() {
        return "发送";
    }

    @Override
    public boolean showRight() {
        return true;
    }

    @Override
    public void toDoRightSomething() {
        if(getCheckedItems().size() == 0){
            ToastUtil.show("请先选择一个");
            return;
        }

        MyForumPostsPOJO.ListBean listBean = getCheckedItems().get(0);
        ForumPostContentBean postContentBean = new ForumPostContentBean();
        postContentBean.setId(listBean.getTid());
        postContentBean.setName(listBean.getTitle());
        String type = listBean.getType() == null ? "0" : listBean.getType();
        String url = "";
        if ("3".equals(type)) {
            //悬赏
            url = BBSShareConstant.BBS_DETAIL_MAP.get("reward") + listBean.getTid();
        } else if ("1".equals(type)) {
            //投票
            url = BBSShareConstant.BBS_DETAIL_MAP.get("vote") + listBean.getTid();
        } else if (listBean.getFid() == 121) {
            //AMA主题帖子
            url = BBSShareConstant.BBS_DETAIL_MAP.get("ama") + listBean.getTid();
        } else if ("5".equals(type)){
            url = BBSShareConstant.BBS_DETAIL_MAP.get("debate") + listBean.getTid();
        }else {
            url = BBSShareConstant.BBS_DETAIL_MAP.get("normal") + listBean.getTid();
        }

        postContentBean.setType(type);
        postContentBean.setUrl(url);

        Intent intent = new Intent();
        intent.putExtra("content", postContentBean.toJsonString());
        intent.putExtra("type", ChatMessage.CONTENT_TYPE_CUSTOM);

        setResult(200, intent);
        finish();

    }

    @Override
    public int showRightImg() {
        return R.drawable.title_bar_compose;
    }

    @Override
    public MyForumPostModelImpl getMyModelImpl() {
        if(mListModel == null){
            mListModel = new MyForumPostModelImpl();
        }
        return mListModel;
    }
}
